<?php
namespace App\Http\Controllers\Admin;
use Maatwebsite\Excel\Facades\Excel;
use App\Exports\ExcelExport;
use App\Utils\ResponseUtil;
use App\DTOS\Admin\AnnouncementSearchDTO;
use App\Services\AnnouncementService;
use App\DTOS\Admin\AnnouncementInsertDTO;
use App\DTOS\Admin\AnnouncementUpdateDTO;
// 游戏公告
class AnnouncementController
{
    private AnnouncementService $service;

    /**
    * AnnouncementService constructor.
    * @param  AnnouncementService $service
    */
    public function __construct(AnnouncementService $service)
    {
        $this->service = $service;
    }

    public function paginate()
    {
        $DTO = new AnnouncementSearchDTO(request()->all());
        $paginate = $this->service->paginate($DTO);
        $data = $paginate->items();
        foreach($data as &$datum){
            $nowDateTime = Date("Y-m-d H:i:s");
            $datum['status'] = $datum['begin_time'] <= $nowDateTime &&  $nowDateTime <= $datum['end_time'] ? 1 : 0;
            $datum['createdAt'] = $datum['created_at']->format("Y-m-d H:i:s");
        }
        $res = [];
        $res['code'] = 0;
        $res['data'] = $data;
        $res['count'] = $paginate->total();
        return ResponseUtil::json($res);
    }

    public function insert()
    {
        try {
            $DTO = new AnnouncementInsertDTO(request()->post());
            $this->service->insert($DTO);
            return ResponseUtil::success();
        } catch (\Exception $e){
            return ResponseUtil::error($e->getMessage());
        }
    }
    public function update($id)
    {
        try{

            $DTO = new AnnouncementUpdateDTO(request()->post());
            $this->service->updateById($id,$DTO);
            return ResponseUtil::success();
        } catch (\Exception $e){
            return ResponseUtil::error($e->getMessage());
        }
    }

    public function delete($id){
        try{
            $this->service->deleteById($id);
            return ResponseUtil::success();
        } catch (\Exception $e){
            return ResponseUtil::error($e->getMessage());
        }
    }
    public function detail($id)
    {
        $data = $this->service->getById($id);
        return ResponseUtil::success($data);
    }

    public function showList()
    {
        $DTO = new AnnouncementSearchDTO(request()->all());
        $DTO->setStatus(1);
        $paginate = $this->service->paginate($DTO);
        $data = collect($paginate->items())->toArray();
        $data = array2_only($data,['id','title','inner_title','content']);
        return ResponseUtil::success($data);
    }

}
